<!--
 * @Descripttion: 编辑课程
 * @Author: xiao li
 * @Date: 2020-09-28 15:24:24
 * @LastEditors: xiao li
 * @LastEditTime: 2021-11-23 15:44:59
-->

<template>
  <div class="lb-goods-edit">
    <top-nav :title="navTitle" :isBack="true"></top-nav>
    <div class="page-main">
      <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
        <el-tab-pane label="课程设置" name="course">
          <div style="height: 40px"></div>
          <el-form
            @submit.native.prevent
            :model="subForm"
            :rules="subFormRules"
            ref="subForm"
            label-width="140px"
            class="sub-form"
          >
            <el-form-item label="课程名称" prop="title">
              <el-input
                type="text"
                v-model="subForm.title"
                placeholder="请输入课程名称"
                maxlength="20"
                show-word-limit
              ></el-input>
            </el-form-item>
            <el-form-item label="课程副标题" prop="subtitle">
              <el-input
                type="text"
                v-model="subForm.subtitle"
                placeholder="请输入课程副标题"
                maxlength="20"
                show-word-limit
              ></el-input>
            </el-form-item>
            <el-form-item label="选择课程分类" prop="cate_id">
              <el-select v-model="subForm.cate_id" placeholder="请选择课程分类">
                <el-option
                  v-for="item in cateOptions"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="观看方式" prop="watch_type">
              <el-radio-group v-model="subForm.watch_type">
                <el-radio :label="0">不限</el-radio>
                <el-radio :label="1">单独付费</el-radio>
                <el-radio :label="2">仅限会员</el-radio>
                <el-radio :label="3"
                  >会员免费+普通用户单独付费购买该课程</el-radio
                >
              </el-radio-group>
              <lb-tool-tips>{{ typeList[subForm.watch_type] }}</lb-tool-tips>
            </el-form-item>
            <el-form
              @submit.native.prevent
              :model="subForm"
              :rules="priceFormRules"
              ref="priceForm"
              label-width="120px"
              class="sub-form"
              :inline="true"
              style="padding-left: 140px; padding-bottom: 0px; margin: 0px"
              v-if="subForm.watch_type === 1 || subForm.watch_type === 3"
            >
              <el-form-item label="" prop="original_price">
                <el-input placeholder v-model="subForm.original_price">
                  <template slot="prepend">原价</template>
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
              <el-form-item label="" prop="price">
                <el-input placeholder v-model="subForm.price">
                  <template slot="prepend">现价</template>
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-form>
            <el-form-item label="虚拟观看次数" prop="pv">
              <el-input
                v-model.number="subForm.pv"
                placeholder="请输入虚拟观看次数"
              ></el-input>
              <lb-tool-tips
                >为促进用户购买量，可设置一个初始观看次数，小程序前端显示的观看次数为：虚拟+真实的计算方式。</lb-tool-tips
              >
            </el-form-item>
            <el-form-item label="排序值" prop="top">
              <el-input-number
                class="lb-input-number"
                v-model="subForm.top"
                :controls="false"
                :precision="0"
                :min="0"
                placeholder="请输入排序值"
              ></el-input-number>
              <lb-tool-tips>值越大, 排序越靠前</lb-tool-tips>
            </el-form-item>
            <el-form-item label="关联商品" prop>
              <!-- <el-form-item label="关联商品" prop v-if="is_shop"> -->
              <el-tag
                :closable="cur_info.name ? true : false"
                @close="delCurInfo"
                @click="chooseCurInfo"
                >{{ cur_info.name || '选择商品' }}</el-tag
              >
            </el-form-item>
            <el-form-item label="封面图" prop="cover">
              <lb-cover
                :fileList="subForm.cover"
                @selectedFiles="getCover"
              ></lb-cover>
              <lb-tool-tips>图片建议尺寸: 750 * 450</lb-tool-tips>
            </el-form-item>
            <el-form-item label="课程介绍" prop="text">
              <lb-ueditor v-model="subForm.text" :destroy="true"></lb-ueditor>
            </el-form-item>
            <el-form-item>
              <div class="space-lg"></div>
              <el-button type="primary" @click="submitGoodsInfo">{{
                $t('action.submit')
              }}</el-button>
              <el-button
                type="default"
                style="margin-left: 10px"
                @click="goBack"
                >{{ $t('action.back') }}</el-button
              >
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="关联视频" name="video" v-if="subForm.id">
          <div style="height: 40px"></div>

          <lb-button
            size="medium"
            type="primary"
            icon="el-icon-plus"
            @click="
              $router.push(
                `${appPath}/payclass/editVideo?class_id=${subForm.id}`
              )
            "
            >{{ $t('menu.PayclassVideoAdd') }}</lb-button
          >
          <div class="space-lg"></div>
          <el-row class="page-search-form">
            <el-form
              @submit.native.prevent
              :inline="true"
              :model="searchForm.video"
              ref="videoForm"
            >
              <el-form-item label="输入查询" prop="title">
                <el-input
                  v-model="searchForm.video.title"
                  placeholder="请输入视频名称"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <lb-button
                  size="medium"
                  type="primary"
                  icon="el-icon-search"
                  style="margin-right: 5px"
                  @click="getTableDataList(1, 'video')"
                  >{{ $t('action.search') }}</lb-button
                >
                <lb-button
                  size="medium"
                  icon="el-icon-refresh-left"
                  @click="resetForm('video')"
                  >{{ $t('action.reset') }}</lb-button
                >
              </el-form-item>
            </el-form>
          </el-row>
          <el-table
            v-loading="loading.video"
            :data="tableData.video"
            :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
            tooltip-effect="dark"
            style="width: 100%"
          >
            <el-table-column prop="title" width="170" label="视频名称">
            </el-table-column>
            <el-table-column prop="url" label="视频链接"> </el-table-column>
            <!-- <el-table-column
              prop="pv"
              label="观看量">
            </el-table-column> -->
            <el-table-column prop="top" label="排序值"> </el-table-column>
            <el-table-column prop="create_time" label="创建时间">
              <template slot-scope="scope">
                <div>{{ scope.row.create_time | handleTime(1) }}</div>
                <div>{{ scope.row.create_time | handleTime(2) }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="status" width="160px" label="操作">
              <template slot-scope="scope">
                <div class="table-operate">
                  <lb-button
                    size="mini"
                    plain
                    type="primary"
                    @click="
                      $router.push(
                        `${appPath}/payclass/editVideo?class_id=${subForm.id}&id=${scope.row.id}`
                      )
                    "
                    >{{ $t('action.edit') }}</lb-button
                  >
                  <lb-button
                    size="mini"
                    plain
                    type="danger"
                    @click="confirmDel(scope.row.id, 'video')"
                    >{{ $t('action.delete') }}</lb-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
          <lb-page
            :batch="false"
            :page="searchForm.video.page"
            :pageSize="searchForm.video.limit"
            :total="total.video"
            @handleSizeChange="handleSizeChange($event, 'video')"
            @handleCurrentChange="handleCurrentChange($event, 'video')"
          >
          </lb-page>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 选择可用商品 -->
    <el-dialog
      title="选择可用商品"
      :visible.sync="showGoods"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :append-to-body="true"
      :before-close="closeGoodsForm"
    >
      <div class="dialog-link-box">
        <div class="link-right" :style="{ width: '100%' }">
          <el-form
            @submit.native.prevent
            :inline="true"
            :model="searchForm.goods"
          >
            <el-form-item label>
              <el-input
                v-model="searchForm.goods.title"
                placeholder="请输入商品名称"
              ></el-input>
            </el-form-item>
            <lb-button
              type="primary"
              @click="handleCurrentChange(1, 'goods')"
              >{{ $t('action.search') }}</lb-button
            >
          </el-form>
          <el-table
            v-loading="loading.goods"
            :data="tableData.goods"
            ref="singleTable"
            highlight-current-row
            @current-change="handleCurrentRow"
            style="width: 100%"
          >
            <el-table-column prop="id" label="ID"></el-table-column>
            <el-table-column prop="name" label="商品名称"></el-table-column>
            <el-table-column prop="cover" label="封面图">
              <template slot-scope="scope">
                <lb-image :src="scope.row.cover[0]" />
              </template>
            </el-table-column>
            <el-table-column
              prop="cate_text"
              label="所属分类"
            ></el-table-column>
            <el-table-column prop="price_text" label="价格"></el-table-column>
            <el-table-column
              prop="sale_count"
              label="累计净销量"
            ></el-table-column>
            <el-table-column prop="stock" label="库存"></el-table-column>
          </el-table>
        </div>
      </div>
      <lb-page
        :batch="false"
        :page="searchForm.goods.page"
        :pageSize="searchForm.goods.limit"
        :total="total.goods"
        @handleSizeChange="handleSizeChange($event, 'goods')"
        @handleCurrentChange="handleCurrentChange($event, 'goods')"
      ></lb-page>

      <div style="text-align: right; margin-top: 20px">
        <el-button @click="closeGoodsForm">取 消</el-button>
        <el-button type="primary" @click="submitGoodsForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { mapState } from 'vuex'
export default {
  data () {
    let validateIntPrice = (rule, value, callback) => {
      if (!/^(([0-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/.test(value)) {
        callback(new Error('请输入正确的金额，最多保留两位小数'))
      } else {
        callback()
      }
    }
    return {
      appPath: '',
      navTitle: '',
      activeName: 'course',
      typeList: {
        0: '不限：无论是普通用户还是会员都是免费无门槛观看；',
        1: '单独付费：无论是会员还是普通用户都需要单独付费购买课程学习；',
        2: '仅限会员：该课程仅限会员才能观看，非会员需要认证成为会员才可以；',
        3: '会员免费+普通用户单独付费购买该课程：会员免费观看，普通用户支持付费购买该课程观看；'
      },
      cateOptions: [],
      is_shop: false,
      currentRow: {},
      showGoods: false,
      cur_info: {
        id: 0,
        name: ''
      },
      searchForm: {
        goods: {
          page: 1,
          limit: 10,
          title: ''
        },
        video: {
          class_id: 0,
          page: 1,
          limit: 10,
          title: ''
        }
      },
      total: {
        goods: 0,
        video: 0
      },
      loading: {
        goods: false,
        video: false
      },
      tableData: {
        goods: [],
        video: []
      },
      // 基本信息表单值
      subForm: {
        id: 0,
        title: '',
        subtitle: '',
        cate_id: '',
        goods_id: 0,
        watch_type: 0,
        original_price: '',
        price: '',
        pv: '',
        top: 0,
        cover: [],
        text: '',
        status: 1
      },
      // 基本信息验证规则
      subFormRules: {
        title: {
          required: true,
          type: 'string',
          message: '请输入课程名称',
          trigger: 'blur'
        },
        subtitle: {
          required: true,
          type: 'string',
          message: '请输入课程副标题',
          trigger: 'blur'
        },
        cate_id: {
          required: true,
          type: 'number',
          message: '请选择课程分类',
          trigger: 'change'
        },
        watch_type: {
          required: true
        },
        pv: {
          required: true,
          type: 'number',
          message: '请输入虚拟观看次数',
          trigger: 'blur'
        },
        top: {
          required: true,
          type: 'number',
          message: '请输入排序值',
          trigger: 'blur'
        },
        cover: {
          required: true,
          type: 'array',
          message: '请上传图片',
          trigger: 'change'
        },
        text: {
          required: true,
          type: 'string',
          message: '请输入课程介绍',
          trigger: 'blur'
        }
      },
      priceFormRules: {
        original_price: { required: true, validator: validateIntPrice, trigger: 'blur' },
        price: { required: true, validator: validateIntPrice, trigger: 'blur' }
      }
    }
  },
  async created () {
    let { path } = this.$route
    this.appPath = path.includes('app/') ? '/app' : ''
    console.log('appPath =>', this.appPath, this.$route, path)
    let { id } = this.$route.query
    if (!id && this.routesItem.isPayclassTab.id) {
      id = this.routesItem.isPayclassTab.id
    }
    this.activeName = this.routesItem.isPayclassTab.isTab
    this.subForm.id = id
    this.navTitle = this.$t(id ? 'menu.PayclassCourseEdit' : 'menu.PayclassCourseAdd')
    await this.getCateList()
    await this.getTableDataList(1, this.routesItem.isPayclassTab === 'course' ? 'goods' : 'video')
    if (id) {
      await this.getDetail()
    }
  },
  computed: {
    ...mapState({
      routesItem: state => state.routes
    })
  },
  methods: {
    async getCateList () {
      let { code, data } = await this.$api.payclassCateSelect()
      if (code !== 200) return
      this.cateOptions = data
    },
    handleSizeChange (val, key) {
      this.searchForm[key].limit = val
      this.handleCurrentChange(1, key)
    },
    handleCurrentChange (val, key) {
      this.searchForm[key].page = val
      this.getTableDataList('', key)
    },
    /**
     * @method: 获取列表：关联商品/视频列表
     */
    async getTableDataList (flag, key) {
      if (flag) this.searchForm[key].page = 1
      this.loading[key] = true
      let searchForm = this.searchForm[key]
      searchForm.class_id = this.subForm.id
      let methodModel = key === 'goods' ? 'getBaseGoodsSelect' : 'payclassVideoList'
      let { code, data } = await this.$api[methodModel](searchForm)
      this.loading[key] = false
      if (code !== 200) return
      this.tableData[key] = data.data
      this.total[key] = data.total
    },
    async getSelectOptions () {
      let { code, data } = await this.$api.restaurantCateSelect()
      if (code !== 200) return
      this.cateOptions = data
    },
    /**
     * @method 获取课程详情
     */
    async getDetail () {
      let { id = 0 } = this.subForm
      if (!id) return
      let { code, data } = await this.$api.payclassClassInfo({ id })
      if (code !== 200) return
      data.cover = [{ url: data.cover }]
      for (let key in this.subForm) {
        this.subForm[key] = data[key]
      }
      this.cur_info = { id: data.goods_id, name: data.goods_name }
    },
    handleClick (e) {
      let key = e.label === '课程设置' ? 'goods' : 'video'
      this.getTableDataList(1, key)
      if (key === 'goods' && this.subForm.id) {
        this.getDetail()
      }
    },
    async chooseCurInfo () {
      this.getTableDataList(1, 'goods')
      this.showGoods = true
    },
    delCurInfo () {
      this.cur_info = { id: 0, name: '' }
      this.subForm.goods_id = 0
    },
    handleCurrentRow (e) {
      this.currentRow = e
    },
    submitGoodsForm () {
      let { id = 0, name = '' } = this.currentRow
      if (!id) return
      this.cur_info = { id, name }
      this.subForm.goods_id = id
      this.currentRow = {}
      this.showGoods = false
    },
    /**
     * @method: 重置表单
     */
    resetForm (form) {
      let name = `${form}Form`
      this.$refs[name].resetFields()
      this.getTableDataList(1, form)
    },
    closeGoodsForm () {
      this.searchForm.goods.title = ''
      this.showGoods = false
    },
    /**
     * @method 返回上一页
     */
    goBack () {
      this.$route.meta.refresh = true
      this.$router.back(-1)
    },
    /**
     * @method 获取课程封面图
     */
    getCover (img) {
      this.subForm.cover = img
    },
    /**
     * @method 提交课程信息
     */
    async submitGoodsInfo () {
      let subForm = JSON.parse(JSON.stringify(this.subForm))
      let formArr = ['subForm']
      if (subForm.watch_type === 1 || subForm.watch_type === 3) {
        formArr.push('priceForm')
      }
      let flag = true
      for (let i = 0, len = formArr.length; i < len; i++) {
        this.$refs[formArr[i]].validate(valid => {
          if (!valid) {
            flag = false
            return false
          }
        })
      }
      if (flag) {
        subForm.cover = subForm.cover[0].url
        let methodModel = subForm.id ? 'payclassClassUpdate' : 'payclassClassAdd'
        let { code, data } = await this.$api[methodModel](subForm)
        if (code !== 200) return
        this.subForm.id = subForm.id ? subForm.id : data
        this.searchForm.goods.id = subForm.id ? subForm.id : data
        this.searchForm.video.class_id = subForm.id ? subForm.id : data
        this.$message.success(this.$t(subForm.id ? 'tips.successRev' : 'tips.successSub'))
        this.activeName = 'video'
        this.searchForm.video.page = 1
        this.getTableDataList(1, 'video')
      }
    },
    // 上下架、删除
    updateItem (id, status, key) {
      this.$api.payclassVideoUpdate({ id, status }).then(res => {
        if (res.code === 200) {
          this.$message.success(this.$t(status === -1 ? 'tips.successDel' : 'tips.successOper'))
          if (status === -1) {
            this.searchForm[key].page = this.searchForm[key].page < Math.ceil((this.total[key] - 1) / this.searchForm[key].limit) ? this.searchForm[key].page : Math.ceil((this.total[key] - 1) / this.searchForm[key].limit)
            this.getTableDataList(1, key)
          }
        } else {
          if (status === -1) return
          this.getTableDataList(1, key)
        }
      })
    },
    // 删除
    confirmDel (id, key) {
      this.$confirm(this.$t('tips.confirmDelete'), this.$t('tips.reminder'), {
        confirmButtonText: this.$t('action.comfirm'),
        cancelButtonText: this.$t('action.cancel'),
        type: 'warning'
      }).then(() => {
        this.updateItem(id, -1, key)
      })
    }
  },
  filters: {
    handleTime (val, type) {
      let time = type === 1 ? moment(val * 1000).format('YYYY-MM-DD') : type === 2 ? moment(val * 1000).format('HH:mm:ss') : moment(val * 1000).format('YYYY-MM-DD HH:mm:ss')
      return time
    }
  }
}
</script>

<style lang="scss" scoped>
.parmai_view {
  display: flex;
  flex-wrap: wrap;
}
.lb-goods-edit {
  width: 100%;
  padding-bottom: 0px;
  position: relative;
  .el-form {
    margin: 20px 0;
  }

  .sub-form {
    .el-input,
    .el-input-number,
    .el-cascader,
    .el-select {
      width: 300px;
    }
    .el-textarea {
      width: 600px;
    }
  }
  .add-form {
    margin-left: 180px;
    margin-bottom: 30px;
    width: 800px;
    .el-input,
    .el-input-number {
      width: 160px;
    }
  }

  .specs-info {
    width: 925px;
    margin: 20px 0;
    .el-input-number {
      width: 100px;
    }
    .specs-item {
      width: 100%;
      display: flex;
      margin: 24px 0;

      .item-label {
        color: #606266;
        width: 180px;
        min-width: 180px;
        line-height: 35px;
        padding-right: 12px;
        text-align: right;

        .require {
          color: #f56c6c;
        }
      }

      .item-label-table {
        line-height: 50px;
      }

      .item-value {
        width: 100%;

        .table-bot {
          width: 100%;
          display: flex;
          align-items: center;

          span {
            margin-right: 20px;
          }

          .el-link {
            margin: 0 20px 0 0;
          }
        }
      }

      .item-value-specs-name {
        margin-bottom: 16px;

        .el-button {
          margin-left: 20px;
        }
      }

      .el-tag {
        margin: 5px 10px 5px 0px;
      }

      .input-new-tag {
        width: 90px;
        margin: 5px 10px 5px 0px;
        height: 28px;
        vertical-align: bottom;

        .el-input__inner {
          height: 28px !important;
        }
      }
    }
  }
}

.dialog-inner {
  display: flex;
  justify-text: center;
  align-items: center;
  width: 100%;

  .el-input {
    width: 200px;
  }
}

.fiexd {
  height: 80px;
  position: fixed;
  background-color: rgb(255, 255, 255);
  box-shadow: rgb(240, 240, 240) 1px -2px 8px;
  bottom: 0px;
  left: 300px;
  z-index: 5;
  display: flex;
  padding-left: 100px;
  align-items: center;
}
.flex-warp {
  display: flex;
  flex-wrap: wrap;
}
.spe-tag-img {
  // display: inline-block;
  margin: 10px 10px 0 0;
}
</style>
